package com.bt.interceptor;

import com.bt.constant.JwtClaimsConstant;
import com.bt.context.BaseContext;
import com.bt.properties.JwtProperties;
import com.bt.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description TODO
 * @Author 青
 * @Date 2023-04-29 20:08
 */
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    JwtProperties jwtProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源

        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        /**
         * 判断前台
         */
        String userToken = getToken(request);
        if (userToken != null) {
            //获取令牌
            String token = request.getHeader("token");

            //校验
            try {
                log.info("jwt校验:{}", token);
                Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
                String yddUserId = claims.get(JwtClaimsConstant.YDD_USER_ID).toString();


                //对threadLocal setCurrentId()赋值
                BaseContext.setCurrentId(yddUserId);

                log.info("当前用户id：", yddUserId);

                //通过，放行
                return true;
            } catch (Exception ex) {
                //4、不通过，响应401状态码
                response.setStatus(401);
                return false;
            }
        }


        /**
         * 后台
         */
        String adminToken = getAdminToken(request);
        if (adminToken != null) {
            //获取令牌
            String token = request.getHeader("x-token");

            //校验
            try {
                log.info("jwt校验:{}", token);
                Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
                String sysUserId = (claims.get(JwtClaimsConstant.SYSUser_ID).toString());

                //对threadLocal setCurrentId()赋值
                BaseContext.setCurrentId(sysUserId);

                log.info("当前用户id：", sysUserId);

                //通过，放行
                return true;
            } catch (Exception ex) {
                //4、不通过，响应401状态码
                response.setStatus(401);
                return false;
            }
        }

        response.setStatus(401);
        return false;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }



    // 获取请求头部中的 token 字段
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            token = null;
        }
        return token;
    }

    // 获取请求头部中的 x-token 字段
    private String getAdminToken(HttpServletRequest request) {
        String adminToken = request.getHeader("x-token");
        if (!StringUtils.hasText(adminToken)) {
            adminToken = null;
        }
        return adminToken;
    }
}
